<!--
 * @Author: 王灿
 * @Date: 2019-10-27 00:40:05
 * @LastEditTime: 2020-04-18 11:12:54
 * @Description: 登录
 * @FilePath: \scarlet-sparrow-admin\src\views\login\login-form\index
-->
<template>
  <el-form class="login-form">
    <!-- 密码登录 -->
    <el-form-item class="login-form__tag">
      <el-tag type effect="dark">密码登录</el-tag>
    </el-form-item>
    <!-- 手机号 -->
    <el-form-item class="login-form__mobile" prop="mobile">
      <el-input
        type="tel"
        v-model="formData.mobile"
        placeholder="请输入手机号"
        autocomplete="off"
        maxlength="11"
        clearable
        @blur="validatePhone(formData.mobile)"
      ></el-input>
    </el-form-item>
    <!-- 密码 -->
    <el-form-item class="login-form__pass" prop="pwd">
      <el-input
        type="password"
        v-model="formData.pwd"
        placeholder="请输入密码"
        autocomplete="off"
        clearable
        @blur="validatePass(formData.pwd)"
      ></el-input>
    </el-form-item>
    <!-- 验证码 -->
    <el-form-item class="login-form__code" prop="captcha">
      <el-input
        class="login-form__code-input"
        type="text"
        v-model="formData.captcha"
        placeholder="请输入验证码"
        autocomplete="off"
        clearable
        @input="validateCode(formData.captcha)"
        @keyup.enter.native="onSubmit"
      ></el-input>
      <img
        class="login-form__code-img"
        :src="codeUrl"
        alt
        v-if="!isLoading"
        @click="onGetCaptcha"
      />
      <img class="login-form__code-img" :src="codeUrl" alt v-else />
    </el-form-item>
    <!-- 按钮 -->
    <el-form-item class="login-form__btn">
      <el-button type="primary" @click="onSubmit" :loading="isLoading"
        v-permissions="'sysLogins'">登 录</el-button
      >
      <span class="login-form__btn-forget" @click="onChangeFlag">忘记密码</span>
    </el-form-item>
  </el-form>
</template>

<script>
import { storageSetItem, storageGetItem, storageRemoveItem } from '@/utils/index.js'
import { getCaptcha, getLoginAdmin } from '@/api/login.js'
export default {
  name: 'LoginForm',
  data() {
    return {
      formData: {
        mobile: '',
        pwd: '',
        captcha: '',
        key: ''
      },
      codeUrl: '',
      errMsg: '',
      isPhone: false,
      isPassword: false,
      isCode: false,
      lv: 0,
      isLoading: false
    }
  },
  created() {
    // 清空头部导航
    storageRemoveItem('editableTabs')
    storageRemoveItem('editableTabsValue')
    if (storageGetItem('mobile')) {
      this.formData.mobile = storageGetItem('mobile')
      this.formData.pwd = storageGetItem('pwd')
      this.isPhone = true
      this.isPassword = true
    }
    this.onGetCaptcha()
  },
  watch: {
    // 监听手机号错误
    errMsg() {
      if (!this.isPhone || !this.isPassword || !this.isCode) {
        this.onErrorMsg(this.errMsg)
      }
    },
    // 监听输入验证码
    'formData.captcha'(newVal) {
      if (newVal.length === 4 && this.isPhone && this.isPassword) {
        this.onSubmit()
      }
    }
  },
  methods: {
    // 获取图形验证码
    onGetCaptcha() {
      this.formData.key = this.getKey()
      getCaptcha({ key: this.formData.key }).then(res => {
        this.codeUrl =
          process.env.VUE_APP_USER_URL + '/captcha.jpg?key=' + this.formData.key
      })
    },
    // 校验手机号码格式
    validatePhone(value) {
      if (!value) {
        this.isPhone = false
        this.errMsg = '请输入手机号'
        return false
      } else {
        const tel = /^1[3456789]\d{9}$/
        if (tel.test(value)) {
          this.isPhone = true
          return true
        } else {
          this.isPhone = false
          this.errMsg = '手机号格式不正确'
          return false
        }
      }
    },
    // 校验密码
    validatePass(value) {
      if (value === '') {
        this.errMsg = '请输入密码'
        this.isPassword = false
        return false
      } else {
        this.lv = 0 // 密码强度等级
        if (value.length >= 6 && value.length <= 20) {
          // if (value.match(/[a-z]/g)) { this.lv++ } // 含有小写字母
          // if (value.match(/[A-Z]/g)) { this.lv++ } // 含有大写字母
          // if (value.match(/[0-9]/g)) { this.lv++ } // 含有数字
          // if (value.match(/[\-\_\,\!\|\~\`\(\)\#\$\%\^\&\*\{\}\:\;\"\L\<\>\?]/g)) { this.lv++ } // 含有特殊字符
          // if (this.lv >= 2) { // 满足其中两项时,查询密码强度
          //   this.isPassword = true
          //   return true
          // } else {
          //   this.isPassword = false
          //   this.errMsg = '密码应为6~20位，数字、字母、符号两种及以上组合'
          //   return false
          // }
          this.isPassword = true
          return true
        } else {
          this.isPassword = false
          this.errMsg = '密码应为6~20位，数字、字母、符号两种及以上组合'
          return false
        }
      }
    },
    // 校验验证码
    validateCode(value) {
      if (value === '') {
        this.errMsg = '请输入验证码'
        this.isCode = false
        return false
      } else {
        this.isCode = true
        return true
      }
    },
    // 获取key
    getKey() {
      var len = 32 //  32长度
      var radix = 16 //  16进制
      var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(
        ''
      )
      var uuid = [],
        i
      radix = radix || chars.length
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
      } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16)
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
          }
        }
      }
      return uuid.join('')
    },
    // 登录按钮
    onSubmit() {
      // do something
      this.isLoading = false
      if (this.isPhone && this.isPassword && this.isCode) {
        this.isLoading = true
        getLoginAdmin(this.formData)
          .then(res => {
            storageSetItem('mobile', this.formData.mobile)
            storageSetItem('pwd', this.formData.pwd)
            storageSetItem('accessToken', res.data.accessToken)
            storageSetItem('userId', res.data.userId)
            storageSetItem('type', res.data.type)
            this.$router.push('/home-user')
          })
          .catch(res => {
            this.isLoading = false
            this.isCode = false
            this.formData.captcha = ''
            this.onGetCaptcha()
          })
      }
    },
    // 页面跳转
    onChangeFlag() {
      this.$emit('onChangeFlag', { isLogin: false, isForget: true })
    },
    // 错误消息
    onErrorMsg(errMsg) {
      this.$notify.error({
        title: '提示',
        message: errMsg
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-form {
  width: 430px;
  height: 320px;
  box-shadow: 0 0 1px 1px #ddd;
  background: $navBarTitle;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -270px;
  margin-top: -200px;
  border-radius: 6px;
  padding: 40px;
  .login-form__btn {
    margin-top: 30px;
    button {
      width: 100%;
    }
  }
}
</style>

<style lang="scss">
.login-form {
  .el-form-item {
    margin-bottom: 20px;
    .el-input__inner {
      height: 40px;
    }
    .el-input__suffix {
      height: 40px;
    }
  }
  .login-form__code {
    .el-form-item__content {
      @include row;
      .login-form__code-img {
        height: 38px;
        border-radius: 4px;
        cursor: pointer;
        margin-left: 10px;
      }
    }
  }
  .login-form__btn {
    .el-form-item__content {
      @include column;
      align-items: flex-end;
      .login-form__btn-forget {
        line-height: 36px;
        cursor: pointer;
        padding: 0 10px;
      }
    }
  }
}
</style>
